package com.kakarote.hbase.config;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class HdfsTemplate {

    private final Configuration hadoopConfig;

    public HdfsTemplate() {
        hadoopConfig = new Configuration();
        hadoopConfig.set("fs.defaultFS", "hdfs://localhost:9000");
    }

    public void writeFile(String hdfsPath, String content) throws IOException {
        Path path = new Path(hdfsPath);
        try (FSDataOutputStream outputStream = FileSystem.get(hadoopConfig).create(path)) {
            outputStream.writeBytes(content);
        }
    }

    public String readFile(String hdfsPath) throws IOException {
        Path path = new Path(hdfsPath);
        try (FSDataInputStream inputStream = FileSystem.get(hadoopConfig).open(path)) {
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        }
    }
}
